package com.aiyige.page.edituserinfo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.User;
import com.aiyige.page.edituserinfo.adapter.EditUserBannerAdapter;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UploadPhotoUtil;
import com.aiyige.utils.banner.BannerAdapter;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

@Route(path = ARouterConfig.EditUserIntroductionBannerPage)
public class EditUserIntroductionBannerPage extends AppCompatActivity {
    public static final int REQUEST_CODE_ADD_BANNER = 1;
    public static final int REQUEST_CODE_EDIT_BANNER_IMAGE = 2;
    public static final int REQUEST_CODE_ADD_BANNER_URL = 3;
    public static final int REQUEST_CODE_EDIT_BANNER_URL = 4;
    public static final int MAX_INTRODUCTION_LENGTH = 200;
    public static final int MAX_BANNER_NUM = 6;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.titleBar)
    RelativeLayout titleBar;
    @BindView(R.id.inputNumTv)
    TextView inputNumTv;
    @BindView(R.id.totalInputNumTv)
    TextView totalInputNumTv;
    @BindView(R.id.bannerRv)
    RecyclerView bannerRv;
    @BindView(R.id.introductionEt)
    EditText introductionEt;
    EditUserBannerAdapter editUserBannerAdapter;
    EditBannerBottomDialog editBannerBottomDialog;
    int editPosition = 0;
    InputNumFilter inputNumFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_user_introduction_banner);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        inputNumFilter = new InputNumFilter(MAX_INTRODUCTION_LENGTH);
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                inputNumTv.setText(num + "");
            }
        });
        introductionEt.setFilters(new InputFilter[]{inputNumFilter});
        editBannerBottomDialog = EditBannerBottomDialog.newInstance();
        editBannerBottomDialog.setListener(new EditBannerBottomDialog.Listener() {
            @Override
            public void editPhoto(int position) {
                editPosition = position;
                PictureSelector.create(EditUserIntroductionBannerPage.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(true)
                        .isCamera(true)
                        .enableCrop(true)
                        .sizeMultiplier(0.5f)
                        .withAspectRatio(720, 358)
                        .freeStyleCropEnabled(false)
                        .previewEggs(true)
                        .forResult(REQUEST_CODE_EDIT_BANNER_IMAGE);
            }

            @Override
            public void editUrl(int position) {
                editPosition = position;
                ARouter.getInstance().build(ARouterConfig.EditBannerUrlPage)
                        .withString("imageUrl", editUserBannerAdapter.getItem(position).getUrl())
                        .withString("bannerUrl", editUserBannerAdapter.getItem(position).getLink())
                        .navigation(EditUserIntroductionBannerPage.this, REQUEST_CODE_EDIT_BANNER_URL);
            }

            @Override
            public void delete(int position) {
                if (editUserBannerAdapter.getItemCount() == MAX_BANNER_NUM && editUserBannerAdapter.getItem(editUserBannerAdapter.getItemCount() - 1) != BannerAdapter.Data.DUMMY_ITEM) {
                    editUserBannerAdapter.remove(position);
                    editUserBannerAdapter.addData(BannerAdapter.Data.DUMMY_ITEM);
                } else {
                    editUserBannerAdapter.remove(position);
                }
            }
        });
        bannerRv.setLayoutManager(new GridLayoutManager(this, 2));
        editUserBannerAdapter = new EditUserBannerAdapter();
        editUserBannerAdapter.addData(BannerAdapter.Data.DUMMY_ITEM);
        editUserBannerAdapter.bindToRecyclerView(bannerRv);
        editUserBannerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (editUserBannerAdapter.getItem(position).equals(BannerAdapter.Data.DUMMY_ITEM)) {
                    PictureSelector.create(EditUserIntroductionBannerPage.this)
                            .openGallery(PictureMimeType.ofImage())
                            .imageSpanCount(4)
                            .selectionMode(PictureConfig.SINGLE)
                            .previewImage(true)
                            .isCamera(true)
                            .enableCrop(true)
                            .sizeMultiplier(0.5f)
                            .withAspectRatio(720, 358)
                            .freeStyleCropEnabled(false)
                            .previewEggs(true)
                            .forResult(REQUEST_CODE_ADD_BANNER);
                } else {
                    editBannerBottomDialog.setPosition(position);
                    editBannerBottomDialog.show(getSupportFragmentManager(), "");
                }
            }
        });
        requestData();

    }


    public void doSave() {
        List<User.SlideImage> slideImageList = new LinkedList<>();
        for (BannerAdapter.Data item : editUserBannerAdapter.getData()) {
            if (item == BannerAdapter.Data.DUMMY_ITEM) continue;
            slideImageList.add(User.SlideImage.newBuilder()
                    .url(item.getUrl())
                    .router(item.getLink())
                    .title(item.getTitle())
                    .build());
        }
        new SaveTask(this, slideImageList, introductionEt.getText().toString()).execute();
    }


    public class SaveTask extends SafeAsyncTask<Object, Object, Object> {
        List<User.SlideImage> slideImageList;
        String introduction;


        public SaveTask(Activity activity, List<User.SlideImage> slideImageList, String introduction) {
            super(activity, R.string.text_process);
            this.slideImageList = slideImageList;
            this.introduction = introduction;
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder()
                                .moreBackup(User.MoreBackup.newBuilder().introduce(introduction).build())
                                .slideBackup(slideImageList).build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                User tempUser = JSON.parseObject(json, User.class);
                User user = AccountUtil.getCurrentUser();
                user.setSlideBackup(tempUser.getSlideBackup());
                AccountUtil.updateCurrentUser(user);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                ToastX.show(R.string.edit_user_page_success);
                finish();
            }
        }
    }


    public void requestData() {
        new RequestDataTask(this).execute();
    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        List<User.SlideImage> slideImageList = new LinkedList<>();

        public RequestDataTask(Activity activity) {
            super(activity, R.string.loading);
        }


        @Override
        protected Object doInBackground(Object... objects) {
            try {
                if (AccountUtil.isLogin()) {
                    Response<ResponseBody> response = ApiManager.getService()
                            .userCenterUsers(AccountUtil.getCurrentUser().getId())
                            .execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = response.body().string();
                    User tempUser = JSON.parseObject(json, User.class);
                    User user = AccountUtil.getCurrentUser();
                    user.update(tempUser);
                    AccountUtil.updateCurrentUser(user);
                    return null;
                } else {
                    throw new Exception(StringUtils.getString(R.string.not_login));
                }
            } catch (Exception e) {
                return e;
            }
        }


        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                updateView();
            }
        }
    }

    public void updateView() {
        introductionEt.setText(AccountUtil.getCurrentUser().getMoreBackup().getIntroduce());
        if (!ListUtil.isEmpty(AccountUtil.getCurrentUser().getSlideBackup())) {
            List<BannerAdapter.Data> editUserBannerItemList = new LinkedList<>();
            for (User.SlideImage slideImage : AccountUtil.getCurrentUser().getSlideBackup()) {
                BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                bannerAdapterData.setId(slideImage.getId());
                bannerAdapterData.setTitle(slideImage.getTitle());
                bannerAdapterData.setUrl(slideImage.getUrl());
                bannerAdapterData.setLink(slideImage.getRouter());
                bannerAdapterData.setRouter(slideImage.getRouter());
                editUserBannerItemList.add(bannerAdapterData);
            }
            if (editUserBannerItemList.size() < MAX_BANNER_NUM) {
                editUserBannerItemList.add(BannerAdapter.Data.DUMMY_ITEM);
            }
            editUserBannerAdapter.setNewData(editUserBannerItemList);
        }
    }


    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                doSave();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_ADD_BANNER: {
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia item : selectList) {
                        String path;
                        if (item.isCompressed()) {
                            path = item.getCompressPath();
                        } else if (item.isCut()) {
                            path = item.getCutPath();
                        } else {
                            path = item.getPath();
                        }
                        final BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                        bannerAdapterData.setUrl(path);
                        bannerAdapterData.setLink("");
                        editUserBannerAdapter.addData(editUserBannerAdapter.getItemCount() - 1, bannerAdapterData);
                        if (editUserBannerAdapter.getItemCount() > MAX_BANNER_NUM) {
                            editUserBannerAdapter.remove(editUserBannerAdapter.getItemCount() - 1);
                        }
                        UploadPhotoUtil.newBuilder()
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(EditUserIntroductionBannerPage.this)
                                                .message(R.string.uploading)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {
                                        Timber.e("onProgress:" + progress);
                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(t.getMessage());
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        bannerAdapterData.setUrl(url);
                                        loadingDialog.dismiss();
                                    }
                                }).photoLocalUrl(bannerAdapterData.getUrl())
                                .build()
                                .upload();
                        break;
                    }
                }
                break;
            }

            case REQUEST_CODE_EDIT_BANNER_URL: {
                if (resultCode == RESULT_OK) {
                    BannerAdapter.Data bannerAdapterData = editUserBannerAdapter.getItem(editPosition);
                    bannerAdapterData.setUrl(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_IMAGE_URL));
                    bannerAdapterData.setLink(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_URL));
                    editUserBannerAdapter.setData(editPosition, bannerAdapterData);
                }
                break;
            }
            case REQUEST_CODE_ADD_BANNER_URL: {
                if (resultCode == RESULT_OK) {
                    final BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                    bannerAdapterData.setUrl(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_IMAGE_URL));
                    bannerAdapterData.setLink(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_URL));
                    editUserBannerAdapter.addData(editUserBannerAdapter.getItemCount() - 1, bannerAdapterData);
                    if (editUserBannerAdapter.getItemCount() > MAX_BANNER_NUM) {
                        editUserBannerAdapter.remove(editUserBannerAdapter.getItemCount() - 1);
                    }
                    UploadPhotoUtil.newBuilder()
                            .listener(new UploadPhotoUtil.Listener() {
                                LoadingDialog loadingDialog;

                                @Override
                                public void onPreUpload() {
                                    loadingDialog = LoadingDialog.newBuilder()
                                            .with(EditUserIntroductionBannerPage.this)
                                            .message(R.string.uploading)
                                            .show();
                                }

                                @Override
                                public void onProgress(double progress) {
                                    Timber.e("onProgress:" + progress);
                                }

                                @Override
                                public void onFail(Throwable t) {
                                    loadingDialog.dismiss();
                                    ToastX.show(t.getMessage());
                                }

                                @Override
                                public void onFinish(String url) {
                                    bannerAdapterData.setUrl(url);
                                    loadingDialog.dismiss();
                                }
                            }).photoLocalUrl(bannerAdapterData.getUrl())
                            .build()
                            .upload();
                }
                break;
            }

            case REQUEST_CODE_EDIT_BANNER_IMAGE: {
                if (resultCode == RESULT_OK) {
                    final BannerAdapter.Data bannerAdapterData = editUserBannerAdapter.getItem(editPosition);
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (ListUtil.isEmpty(selectList)) {
                        break;
                    }
                    String path;
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCompressed()) {
                        path = localMedia.getCompressPath();
                    } else if (localMedia.isCut()) {
                        path = localMedia.getCutPath();
                    } else {
                        path = localMedia.getPath();
                    }
                    bannerAdapterData.setUrl(path);
                    editUserBannerAdapter.setData(editPosition, bannerAdapterData);
                    UploadPhotoUtil.newBuilder()
                            .listener(new UploadPhotoUtil.Listener() {
                                LoadingDialog loadingDialog;

                                @Override
                                public void onPreUpload() {
                                    loadingDialog = LoadingDialog.newBuilder()
                                            .with(EditUserIntroductionBannerPage.this)
                                            .message(R.string.uploading)
                                            .show();
                                }

                                @Override
                                public void onProgress(double progress) {
                                    Timber.e("onProgress:" + progress);
                                }

                                @Override
                                public void onFail(Throwable t) {
                                    loadingDialog.dismiss();
                                    ToastX.show(t.getMessage());
                                }

                                @Override
                                public void onFinish(String url) {
                                    bannerAdapterData.setUrl(url);
                                    loadingDialog.dismiss();
                                }
                            }).photoLocalUrl(path)
                            .build()
                            .upload();
                }
            }
            default: {
                super.onActivityResult(requestCode, resultCode, data);
                break;
            }
        }
    }
}
